package ter.find.pattern.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import ter.find.pattern.BaseSymbolClassModel;
import ter.find.pattern.ReadWriteFile;

import com.ter.Form;
import com.ter.Range;

public class ChangeForm extends JPanel {



	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField up=new JTextField();
	private JTextField up2=new JTextField();
	private JTextField down=new JTextField();
	private JTextField down2=new JTextField();
	private JTextField symb1=new JTextField();
	private JTextField symb2=new JTextField();
	private JTextField symb3=new JTextField();
	private JTextField symb4=new JTextField();
	private JTextField symb5=new JTextField();

	private JCheckBox indice1=new JCheckBox();
	private JCheckBox indice2=new JCheckBox();


	private JTextField constant=new JTextField();

	private JLabel lindice1=new JLabel("Générer Symbole");
	private JLabel lindice2=new JLabel("Changer");
	private JLabel ul=new JLabel();
	private JLabel ul2=new JLabel();
	private JLabel dl=new JLabel();
	private JLabel dl2=new JLabel();
	private JLabel sl1=new JLabel("Symbole");
	private JLabel sl2=new JLabel("Symbole");
	private JLabel sl3=new JLabel("Symbole");
	private JLabel sl4=new JLabel("Symbole");
	private JLabel sl5=new JLabel("Symbole");
	private JLabel choix=new JLabel("Critère de découpage");

	private JLabel cl=new JLabel();

	private JButton generate=new JButton("générer");
	private JButton save=new JButton("Enregistrer");
	private JButton bseq=new JButton("séquence");
	String[] chose={"demi-journée","par jours","par semaine","par mois","par an"};
	private JComboBox<String> choice=new JComboBox<>(chose); 
	static String varTemp;
	
	private JPanel control=new JPanel();
	private JPanel panRight=new JPanel();

	private JPanel pan1=new JPanel();
	private JPanel pan2=new JPanel();
	private JPanel pan3=new JPanel();
	private JPanel pan4=new JPanel();
	private JPanel pan5=new JPanel();
	private JPanel panControl=new JPanel();
	private JFileChooser fileChose=new JFileChooser();

	private String s1;
	private String s2;
	private String s3;
	private String s4;
	private String s5;
	private double v1;
	private double v2;
	private double v3;
	private double v4;
	private double v5;
	public StringBuffer dataPrint = new StringBuffer(200);
	List<SymbolClass> listeSymbClass2=new ArrayList<SymbolClass>();
	private SlideContainer slideContainer2 = new SlideContainer(1000,200);
	public ChangeForm() {
		super();
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		fileChose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		indice1.setPreferredSize(new Dimension(25, 25));
		indice1.setBackground(Color.red);
		indice1.setSelected(false);
		indice1.setEnabled(false);
		indice2.setPreferredSize(new Dimension(25, 25));
		indice2.setBackground(Color.red);
		indice2.setSelected(false);
		indice2.setEnabled(false);
		
		ul.setText("Petite variation (n3>0)");
		up.setPreferredSize(new Dimension(80, 20));
		
		
		pan1.setBorder(new TitledBorder("Petite augmentation"));
		symb1.setPreferredSize(new Dimension(80, 20));
		pan1.add(ul);
		pan1.add(up);
		pan1.add(sl1);
		pan1.add(symb1);

		ul2.setText("Grande variation (n4>0");

		up2.setPreferredSize(new Dimension(80, 20));
		symb2.setPreferredSize(new Dimension(80, 20));
		pan2.setBorder(new TitledBorder("Grande augmentation"));
		pan2.add(ul2);
		pan2.add(up2);
		pan2.add(sl2);
		pan2.add(symb2);

		dl.setText("Petite variation (n2<0)");
		down.setPreferredSize(new Dimension(80, 20));
		//down.setText("valeur");
		pan3.setBorder(new TitledBorder("petite diminution"));
		symb3.setPreferredSize(new Dimension(80, 20));
		pan3.add(dl);
		pan3.add(down);
		pan3.add(sl3);
		pan3.add(symb3);

		dl2.setText("Grange variation (n1<0)");
		down2.setPreferredSize(new Dimension(80, 20));
		//down2.setText("valeur");
		pan4.setBorder(new TitledBorder("Grande diminution"));
		symb4.setPreferredSize(new Dimension(80, 20));
		pan4.add(dl2);
		pan4.add(down2);
		pan4.add(sl4);
		pan4.add(symb4);

		cl.setText("Pas de variation");
		constant.setPreferredSize(new Dimension(80, 20));
		//constant.setText("valeur");
		pan5.setBorder(new TitledBorder("Constante"));
		symb5.setPreferredSize(new Dimension(80, 20));
		pan5.add(cl);
		pan5.add(constant);
		pan5.add(sl5);
		pan5.add(symb5);

		panControl.setBorder(new TitledBorder("Action"));
		panControl.add(choix);
		panControl.add(choice);
		panControl.add(generate);
		panControl.add(bseq);
		//panControl.add(save);
		panControl.add(lindice1);panControl.add(indice1);
		panControl.add(lindice2);panControl.add(indice2);

		control.add(pan4);
		control.add(pan3);		
		control.add(pan1);
		control.add(pan2);

		control.add(pan5);
		control.add(panControl);
		control.setLayout(new BoxLayout(control, BoxLayout.Y_AXIS));
		control.setBorder(new TitledBorder("Variation"));

		//panRight.setLayout(new FlowLayout(FlowLayout.RIGHT));
		panRight.setBorder(new TitledBorder("Symbole-Intervalle"));
		panRight.add(slideContainer2);

		this.add(control,BorderLayout.EAST);
		this.add(panRight,BorderLayout.WEST);

		generate.addActionListener(new MyActionListener());
		save.addActionListener(new MyActionListener());
		bseq.addActionListener(new MyActionListener());
		up.addActionListener(new MyActionListener());
		up2.addActionListener(new MyActionListener());
		symb1.addActionListener(new MyActionListener());
		symb2.addActionListener(new MyActionListener());
		symb3.addActionListener(new MyActionListener());
		symb4.addActionListener(new MyActionListener());
		symb5.addActionListener(new MyActionListener());
		choice.addActionListener(new MyActionListener());
	}



	public class MyActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			Object selec = e.getSource();
			if(selec.equals(generate)){
				List<ValeurSymbol> vs=new ArrayList<ValeurSymbol>();
				List<ValClass> vc=new ArrayList<ValClass>();
				System.out.println("generer");
				try{
					v1=Integer.parseInt(up.getText()); 	 //valeur petite augementation				
					v2=Integer.parseInt(up2.getText()); // valeur grande augmentation
					v3=Integer.parseInt(down.getText()); //valeur petite diminution
					v4=Integer.parseInt(down2.getText());  //valeur grande diminution
					v5=Integer.parseInt(constant.getText());
				}catch(NumberFormatException numberr){
					JOptionPane.showMessageDialog(null, "Entrer les valeurs!");
				}				
				if(symb1.getText().equals("")|| symb2.getText().equals("")|| symb3.getText().equals("")||symb4.getText().equals("")||
						symb5.getText().equals("")){
					JOptionPane.showMessageDialog(null, "Erreur de Symbole! (Entrez un caractère)");
				}
				s1=symb1.getText();
				s2=symb2.getText();
				s3=symb3.getText();
				s4=symb4.getText();
				s5=symb5.getText();
				if(v3 <0 && v4 <0 && v4<v3 && v1>0 && v2>0 && v1<v2){
					vs.add(new ValeurSymbol(v4, s4)); //D
					vs.add(new ValeurSymbol(v3, s3)); //d
					vs.add(new ValeurSymbol(v1, s1)); //u
					vs.add(new ValeurSymbol(v2, s2)); //U					
					vs.add(new ValeurSymbol(v5, s5));


					initiateValue(Form.getClassDiff(), vc); //param class,tabdiff,liste



					List<SymbolClass> listeSymbClass=translateValue(vs, vc);// vc normalement la liste des classes à initialiser
					listeSymbClass2=listeSymbClass;
					BaseSymbolClassModel bs=new BaseSymbolClassModel(listeSymbClass);
					SymbolClassPanel pansym=new SymbolClassPanel(bs);
					indice1.setSelected(true);
					indice1.setBackground(Color.green);
					slideContainer2.add(pansym);
					panRight.updateUI();

				}else{
					indice1.setBackground(Color.red);
					JOptionPane.showMessageDialog(null, "Vérifier l'ordre des valeurs\n n1<n2<0 ,0<n3<n4");
				}



			}


			if(selec.equals(save)){
				if(dataPrint.length()!=0){
					int returnVal = fileChose.showSaveDialog(ChangeForm.this);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fileChose.getSelectedFile();
						String topath=file.getAbsolutePath();
						System.out.println(topath);
						ReadWriteFile rw=new ReadWriteFile();
						try {
							rw.saveToFile(dataPrint.toString(), topath);


						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				}else{
					JOptionPane.showMessageDialog(null, "Please generate Sequence!");
				}


			}


			if(selec.equals(bseq)){

				//System.out.println("generation séquence...");
				String critere=(String) choice.getSelectedItem();
				translateElement(Form.getTabDiff(), listeSymbClass2, critere);// attente du tableau de différence 
				if (JOptionPane.showConfirmDialog(null, "Séquence générer\nSauvegarder? ", "Quitter", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
					if(dataPrint.length()!=0){
						int returnVal = fileChose.showSaveDialog(ChangeForm.this);
						if (returnVal == JFileChooser.APPROVE_OPTION) {
							File file = fileChose.getSelectedFile();
							String topath=file.getAbsolutePath();
							System.out.println(topath);
							ReadWriteFile rw=new ReadWriteFile();
							try {
								rw.saveToFile(dataPrint.toString(), topath);


							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

						}
					}
					
				}
			}
			
			if(selec.equals(choice)){
				indice1.setBackground(Color.red);
				indice2.setBackground(Color.red);
				panRight.updateUI();
			}

		}

	}

	public List<String>  translateElement(Vector<Double> tabdiff,List<SymbolClass> sclass,String critere){ //prend en entrée le tableau de la différence et listeSymboleClass ==> listeSequence
		List<String> sequence=new ArrayList<String>();
		dataPrint.append("#*********** Analyse "+critere+" *****************#");
		double variation;
		double valmin=0,valmax=0;
		String item=null;
		int decoupe=0;
		if(critere.equalsIgnoreCase("demi-journée")){
			decoupe=24;
			varTemp="Journalière (1/2)";
		}else if(critere.equalsIgnoreCase("par jours")){
			decoupe=48;
			varTemp="Journalière";
		}else if(critere.equalsIgnoreCase("par semaine")){
			decoupe=326;
			varTemp="par semaine";
		}else if(critere.equalsIgnoreCase("par mois")){
			decoupe=1440;
			varTemp="par mois";
		}else if(critere.equalsIgnoreCase("par an")){
			decoupe=17520;
			varTemp="annuelle";
		}
		
		if(tabdiff.isEmpty()){
			JOptionPane.showMessageDialog(null, "Please terminate the previous step!");
		}else{
			indice2.setSelected(true);
			indice2.setBackground(Color.green);
			for(int i=0;i<tabdiff.size();i++){			
				variation=tabdiff.get(i);
				
				for(SymbolClass smb:sclass){
					item=smb.getSymb();
					
					valmin=smb.getValeurMin();
					valmax=smb.getValeurMax();
					
					if((variation>=valmin && variation<valmax) || (variation>valmin && variation<=valmax)){
						
						//sequence.add(item);
						dataPrint.append(item);
						dataPrint.append(" ");
					}
					
				}
				if(i%decoupe==0){
					dataPrint.append("-1");
					dataPrint.append(" ");
					dataPrint.append("-2");
					dataPrint.append("\n");
				}
			}
		}

		return sequence;
	}
	
	public static String getCritere(){
		return varTemp;
	}

	public List<SymbolClass> translateValue(List<ValeurSymbol> vs,List<ValClass> vc){
		String symbol=null;
		double val=0,vmin=0,vmax=0;
		double vminD=0,vmaxd=0;
		double vminU=0,vminu=0,vmaxu=0;
		List<SymbolClass> sc=new ArrayList<SymbolClass>();
		for (int i=0;i<vs.size();i++) {
			ValeurSymbol v=vs.get(i);
			symbol=v.getS(); //recupération du symbol
			val=v.getV(); //recupère la valeur , ordre D,d,u,U,c
			//parcourir ici les élements de la liste des classes et chercher la valeur val
			//si v appartient à une classe ==> ajouter sc.add(new SymbolClass(symbol,classe))

			if(i==0){ // cas de Grande diminution
				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					//System.out.println(vmin+" "+vmax);
					if((val>=vmin && val<vmax)||(val>vmin && val<=vmax)){
						vminD=vmin;
						sc.add(new SymbolClass(symbol, vmin, vmax));   //ajout dans la liste SymbolClass des valeurs
					}
				}

				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					if(vmax<vminD){
						sc.add(new SymbolClass(symbol, vmin, vmax));
					}
				}
			}

			if(i==1){ // cas de petite diminution
				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					//System.out.println(vmin+" "+vmax);
					if((val>=vmin && val<vmax)||(val>vmin && val<=vmax)){
						vmaxd=vmax;
						sc.add(new SymbolClass(symbol, vmin, vmax));   //ajout dans la liste SymbolClass des valeurs
					}
				}

				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					if(vmin>vmaxd && vmax<0){
						sc.add(new SymbolClass(symbol, vmin, vmax));
					}
				}
			}

			if(i==2){ // cas de petite augmentation
				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					//System.out.println(vmin+" "+vmax);
					if((val>=vmin && val<vmax)||(val>vmin && val<=vmax)){
						vminu=vmin;
						vmaxu=vmax;
						sc.add(new SymbolClass(symbol, vmin, vmax));   //ajout dans la liste SymbolClass des valeurs
					}
				}

				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					if(vmin>0 && vmax<vminu){
						sc.add(new SymbolClass(symbol, vmin, vmax));
					}
				}
			}

			if(i==3){ // cas d'une grande augmentation
				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					//System.out.println(vmin+" "+vmax);
					if((val>=vmin && val<vmax)||(val>vmin && val<=vmax)){
						vminU=vmin;
						sc.add(new SymbolClass(symbol, vmin, vmax));   //ajout dans la liste SymbolClass des valeurs
					}
				}

				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					if(vmin>vmaxu || vmax<vminU && vmin>vmaxu){
						sc.add(new SymbolClass(symbol, vmin, vmax));
					}
				}
			}

			if(i==4){
				for(ValClass vcc:vc){
					vmin=vcc.getValeurMin();
					vmax=vcc.getValeurMax();
					//System.out.println(vmin+" "+vmax);
					if((val>=vmin && val<vmax)||(val>vmin && val<=vmax)){
						sc.add(new SymbolClass(symbol, 0, 0));   //ajout dans la liste SymbolClass des valeurs
					}
				}
			}



		}

		return sc;
	}

	public void initiateValue(Vector<Range> vr, List<ValClass> vc){
		double valinf=0,valsup=0;
		if(vr.isEmpty()){
			JOptionPane.showMessageDialog(null, "Please terminate the previous step!");
		}else{

			for(Range r:vr){
				valinf=r.getMinval();
				valsup=r.getMaxval();
				vc.add(new ValClass(valinf, valsup));
			}
		}

	}

	public class ValeurSymbol{
		double v;
		String s;
		public ValeurSymbol(double _v,String _s){
			v=_v;
			s=_s;
		}
		public double getV() {
			return v;
		}
		public String getS() {
			return s;
		}

	}

	public class SymbolClass{
		double valeurMin,valeurMax;
		String symb;
		public SymbolClass(String symb,double valeurMin, double valeurMax) {
			super();
			this.valeurMin = valeurMin;
			this.valeurMax = valeurMax;
			this.symb = symb;
		}
		public double getValeurMin() {
			return valeurMin;
		}
		public double getValeurMax() {
			return valeurMax;
		}
		public String getSymb() {
			return symb;
		}

	}

	public class ValClass{
		double valeurMin,valeurMax;

		public ValClass(double valeurMin, double valeurMax) {
			super();
			this.valeurMin = valeurMin;
			this.valeurMax = valeurMax;
		}

		public double getValeurMin() {
			return valeurMin;
		}

		public double getValeurMax() {
			return valeurMax;
		}

		public void setValeurMin(double valeurMin) {
			this.valeurMin = valeurMin;
		}

		public void setValeurMax(double valeurMax) {
			this.valeurMax = valeurMax;
		}



	}


	public static void main(String[] args) {
		JFrame frame = new JFrame("Change Forme");
		frame.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		frame.getContentPane().add(new ChangeForm(),
				BorderLayout.CENTER);
		frame.pack();
		frame.setSize(1050,600);
		frame.setVisible(true);
	}


}
